package com.example.mq.mqsever;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-09-07
 * Time: 14:26
 */

import com.example.mq.common.*;
import com.example.mq.mqsever.core.BasicProperties;

import javax.websocket.RemoteEndpoint;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 本质上就是消息队列本体服务器,一个tcp服务器
 */
public class BrokerServer {
    private ServerSocket serverSocket = null;

    //当前考虑一个BrokerServer上只有一个虚拟主机

    private VirtualHost virtualHost = new VirtualHost("default");
    //此处的key是channelId,value 是对应的Socket对象
    //使用这个哈希表表示当前的所有会话(表示有哪些客户正在和咱们的服务器进行通信)
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<String, Socket>();

    //服务器同时处理多个客户端,引入线程池
    private ExecutorService executorService = null;
    //引入布尔变量控制服务器是否继续运行

    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动!");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                //获取连接
                Socket clientSocket = serverSocket.accept();
                //把连接丢给线程池处理
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止运行!");

        }

    }


    //一般来说停止服务器,就是直接杀死进程
    //此处搞一个单独的停止方法,为了后续的单元测试
    public void stop() throws IOException {
        runnable = false;
        //把线程池的任务都放弃了,让线程都销毁

        executorService.shutdownNow();
        serverSocket.close();
    }


    //通过这个方法来处理一个客户端的连接
    //在这一个连接中,可能会涉及到多个请求和响应
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            //这里需要按照特定的格式来解析字符串并读取,此时需要用到DataInputStream和DataOutPutStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3.把响应写回给客户端
                    writeResponse(dataOutputStream, response);
                }

            } catch (EOFException | SocketException e) {
                //DataInPutStream如果读到EOF,就会抛出一个EOF异常
                //需要借助这个异常来结束循环
                System.out.println("[BrokerServer] connection 关闭! 客户端地址:" + clientSocket.getInetAddress().toString() +
                        ":" + clientSocket.getPort());
            } catch (MqException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.out.println("[BrokerServer] connection出现异常!");
            e.printStackTrace();
        } finally {
            try {
                //当一个连接处理完了,就需要关闭socket
                clientSocket.close();
                //一个tcp连接中,可能有多个channel,需要把这个socket对应的所有channel清理掉
                clearClosedSession(clientSocket);

            } catch (IOException e) {
                e.printStackTrace();

            }

        }

    }


    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        //预期读到的长度
        byte[] payload = new byte[request.getLength()];
        //真实读到的长度
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求格式出错!");
        }
        request.setPayload(payload);
        return request;


    }

    private Response process(Request request, Socket clientSocket) throws IOException, MqException, ClassNotFoundException {
        //处理一次请求,返回一次响应
        //把request的payload进行初步解析
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Request] rid=" + basicArguments.getRid() + ", channelId=" + basicArguments.getChannelId()
                + ", type=" + request.getType() + ", length=" + request.getLength());
        //2.根据type的值,进一步区分这次请求要干啥
        boolean ok = true;
        if (request.getType() == 0x1) {
            //创建一个channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer]创建channel完成! channelId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            //销毁channel
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer]销毁channel完成! channelId=" + basicArguments.getChannelId());

        } else if (request.getType() == 0x3) {
            //创建交换机.此时payload就是ExchangeDeclareArguments对象了
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());

        } else if (request.getType() == 0x4) {
            //删除交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable()
                    , arguments.isExclusive(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());

        } else if (request.getType() == 0x8) {
            QueueUnBindArguments arguments = (QueueUnBindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumeTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        //这个回调函数要做的工作,就是把服务器收到的消息直接推送到对应的消费者客户端
                        @Override
                        public void handlerDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            //先知道这个收到的消息,要发给哪个客户端
                            //此处consumeTag其实是channelId,根据channelId去session中查询,就可以得到对应的socket对象了,就可以往里面发送数据了
                            //1.根据channelId找到socket对象
                            Socket clientSocket = sessions.get(consumerTag);
                            if (consumerTag == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭");
                            }
                            //2.构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setChannelId(consumerTag);
                            subScribeReturns.setRid("");//没有请求只有响应了,所以不需要去对应,rid暂时不需要
                            subScribeReturns.setOk(true);
                            subScribeReturns.setConsumeTag(consumerTag);
                            subScribeReturns.setBasicProperties(basicProperties);
                            subScribeReturns.setBody(body);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);
                            Response response = new Response();
                            //0xc表示服务器给消费者客户推送的数据消息
                            response.setType(0xc);
                            //response的payload就是一个SubScribeReturns

                            response.setLength(payload.length);
                            response.setPayload(payload);
                            //3.把数据写回给客户端
                            //注意此处的dataOutPutStream这个对象不能close
                            //它close了,clientSocket的outputStream也close了,没法源源不断地往客户端写消息了
                            DataOutputStream dataOutputStream = null;
                            try {
                                dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                writeResponse(dataOutputStream, response);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else if (request.getType() == 0xb) {
            //调用basicAck确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        } else {
            //当前的type是非法的
            throw new MqException("[BrokerServer] 未知的type=" + request.getType());

        }
        //3.构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid=" + basicReturns.getRid() + ", channelId=" + basicReturns.getChannelId()
                + ", type=" + response.getType() + ", length=" + response.getLength());
        return response;

    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {

        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());

        //这个刷新缓冲区也是一个重要的操作,让数据快速到网卡里,不是在内存一直呆着
        dataOutputStream.flush();
    }

    private void clearClosedSession(Socket clientSocket) {
        //遍历上述sessions哈希表,把该被关闭的socket对应的键值对都关掉
        List<String> toDeleteChannelId = new ArrayList<>();
        //遍历哈希表
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                //不能边遍历边删除
                //所以再定义一个集合类,遍历另一个集合库删除这里集合的元素
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {

            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理session 完成! 被清理的channelId= " + toDeleteChannelId);

    }


}
